<?php

namespace application\controllers;

use application\BaseController;
use fastphp\facade\Session;

class CaptchaController extends BaseController
{
    public function generate()
    {
        // 生成验证码字符串
        $captchaText = $this->generateCaptchaText();

        // 存储验证码值到会话中
        Session::set('captcha',$captchaText);
//        $_SESSION['captcha'] = $captchaText;

        // 创建验证码图像
        $image = $this->createCaptchaImage($captchaText);

        // 设置响应头并输出图像
        header('Content-Type: image/png');
        imagepng($image);

        // 销毁图像资源
        imagedestroy($image);

        // 退出脚本执行，因为我们已经输出了图像
        exit;
    }

    private function generateCaptchaText($length = 6)
    {
        // 定义验证码字符集（可以包括字母和数字）
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $charactersLength = strlen($characters);
        $captchaText = '';

        // 生成随机字符串作为验证码
        for ($i = 0; $i < $length; $i++) {
            $captchaText .= $characters[rand(0, $charactersLength - 1)];
        }

        return strtolower($captchaText);
    }

    private function createCaptchaImage($text)
    {
        // 设置图像宽度和高度
        $width = 150;
        $height = 50;

        // 创建图像资源
        $image = imagecreatetruecolor($width, $height);

        // 分配颜色
        $backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
        $textColor = imagecolorallocate($image, 0, 0, 0); // 黑色文本
        $lineColor = imagecolorallocate($image, 64, 64, 64); // 灰色干扰线

        // 填充背景色
        imagefilledrectangle($image, 0, 0, $width, $height, $backgroundColor);

        // 添加文本到图像上
        $fontSize = 20;
        $angle = rand(-10, 10); // 随机旋转角度
//        var_dump(APP_PATH . 'public/static/font/picture.ttf');
        $bbox = imagettfbbox($fontSize, $angle, APP_PATH . 'public/static/font/picture.ttf', $text); // 需要一个有效的 TTF 字体文件路径
        $textX = ($width - $bbox[2]) / 2;
        $textY = ($height - $bbox[1]) / 2 + $fontSize;
        imagettftext($image, $fontSize, $angle, $textX, $textY, $textColor, APP_PATH . 'public/static/font/picture.ttf', $text);

        // 添加干扰线
        for ($i = 0; $i < 5; $i++) {
            imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
        }

        // 添加干扰点
        for ($i = 0; $i < 100; $i++) {
            imagesetpixel($image, rand(0, $width), rand(0, $height), $lineColor);
        }

        return $image;
    }
}